<template>
	<basic-container>
		<avue-crud :option="option" :data="data" ref="crud" :table-loading="loading" :permission="permissionList" :page="page"
		@refresh-change="refreshChange" @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange"
		@size-change="sizeChange" @on-load="onLoad">
			<template slot-scope="scope" slot="goodsClassIds">
				<el-button size="mini" type="text" style="color: #606266;" @click="handleRowClick(scope.row)">点击查看</el-button>
			</template>
			<template slot-scope="scope" slot="userName">
				<el-tag color="#fff" style="border: none;color: #333333;"> {{scope.row.userName}} | {{scope.row.trueName}}</el-tag>
			</template>
			<template slot="menuRight">
				<el-button type="primary" size="small" @click="addStore()" >新增</el-button>
			</template>
			<template slot-scope="scope" slot="menu">
				<el-button type="text" size="small" @click="viewStore(scope.row.id)" v-has="'/mall-cloud-base/store/editStoreManage'">查看店铺</el-button>
				<el-button type="text" size="small" v-if="scope.row.isManageStore || scope.row.isAdmin" @click="edit(scope.row.id)" v-has="'/mall-cloud-base/store/editStoreManage'">编辑</el-button>
<!--				<el-button type="text" size="small" @click="viewPic">相册</el-button>-->
				<el-button type="text" size="small" @click="viewPaperWork(scope.row)" v-has="'/mall-cloud-base/store/editStoreManage'">证件</el-button>
			</template>
		</avue-crud>
		<template>
			<el-dialog width="80%" title="相册" top="50px" @close="closeDialog1" center :visible.sync="dialogFormVisible1">
				<avue-form ref="form" v-model="pic" :disabled=isView :option="optionPic" @submit="submit1">
				</avue-form>
			</el-dialog>
			<el-dialog width="40%" title="必要证件" top="200px" @close="closeDialog2" center :visible.sync="dialogFormVisible2">
				<el-checkbox-group v-model="checkList">
					<div class="paperWork" v-for="item in paperWorkList" :key="item.id">
						<el-checkbox :label="item.id" disabled>{{item.name}}</el-checkbox>
						<el-button @click="viewMyPaper(item.imgUrl,item.name)" @mouseover.native="changeColor(item.id)" @mouseout.native="changeColor(item.id)"
						:class="item.isOk?'checkPaper1':'checkPaper'" type="text">[查看]</el-button>
					</div>
				</el-checkbox-group>
				<el-dialog width="30%" :title="workImg.name" :visible.sync="innerVisible" append-to-body center>
					<img align="center" style="width: 60%;height: auto;margin-left: 20%;" :src="workImg.imgUrl" />
				</el-dialog>
			</el-dialog>
			<el-dialog
			  title="经营品类"
			  :visible.sync="currentGoodsVis"
			  width="40%"
			  center>
			  <p style="padding: 10px 20px;color: #000;">{{currentGoodsName}}</p>
			  <p style="padding: 10px 20px;color: #000;">经营品类：</p>
			  <div style="padding: 20px 30px;max-height: 300px;overflow: scroll;line-height: 30px;">
				<el-tree
					:data="currentAreas"
					:default-expanded-keys="[]"
					node-key="id"
					accordion
					ref="goodsClassTree"
					highlight-current
					:props="propsClass"
				></el-tree>
			  </div>
			</el-dialog>
			<store-detail @closeDrawer="closeDrawer" @addOption="addOption"  @callBack='callback' :title="title" :storeId="storeId" :isView="isView" :dialogFormVisible="dialogFormVisible" ></store-detail>
		</template>
	</basic-container>
</template>

<script>
	import storeDetail from '@/components/store/storeDetail'
	import {
		getList,
		update,
		getStoreDetail,
		getParentAndGrandInfoById,
		adminAddUser,
		adminAddStore,
		getGoodsClassTreeNodesByIds
	} from "@/api/base/store/store";
	import {
		mapGetters
	} from "vuex";
	var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
	var DIC = {
		STORETYPE:[{
			label: '自营',
			value: 0
		}, {
			label: '非自营',
			value: 1
		}]
	}
	export default {
		components: {
			storeDetail
		},
		data() {
			return {
				propsClass: {
					label: 'className',
					id: 'id',
					children: 'childrenNodes',
				},
				currentGoodsVis:false,
				currentGoodsName:'',
				currentAreas:'',
				storeId: "",
				// paperWorkList:[],
				paperWorkList: [],
				//证件已选择数组
				checkList: [],
				dialogFormVisible: false, //详情遮罩
				dialogFormVisible1: false, //相册遮罩
				dialogFormVisible2: false, //证件遮罩
				innerVisible: false, //证件照遮罩
				workImg: {},
				isView: false, //当时是否为查看状态
				title: "店铺管理",
				query: {},
				loading: true,
				rolesTree: [],
				rolesKeys: [],
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				//相册数据
				pic: {},
				optionPic: {
					emptyBtn: false,
					submitBtn: false,
				},
				//表单数据
				form: {},
				option: {
					addBtn: false,
					searchBtn: true,
					size: 'mini',
					excelBtn: false,
					tip: false,
					border: true,
					index: false,
					delBtn: false,
					viewBtn: false,
					editBtn: false,
					rowKey: 'id',
					dialogType: 'dialog',
					selectable: (row) => {
						if(row.isManageGoods) {
							return true;
						}else {
							return false;
						}
					},
					align: 'center',
					column: [{
							search: true,
							label: "店铺排序",
							prop: "storeSortByOrderByType",
							dicData:Dict.STORE_SORT_ENUM,
							type:'select',
							hide:true,
							cell: false
						},{
							search: true,
							label: "店铺名称",
							prop: "storeName",
							cell: false
						},
						{
							label: "主对接人",
							prop: "userName",
							cell: false
						},
						{
							label: "主对接人电话",
							prop: "dockingPeoplePhone",
							cell: false
						},
						{
							label: "经营品类",
							prop: "goodsClassIds",
							slot:true,
						},
						{
							label: "到期时间",
							prop: "validity",
							format: 'yyyy-MM-dd',
							valueFormat: 'yyyy-MM-dd',
							type: 'date',
							rules: [{
								required: true,
								message: "请输入有效期",
								trigger: "change"
							}]
						},
						{
							label: "店铺类型",
							prop: "storeType",
							type: "select",
							search: true,
							dicData:DIC.STORETYPE
						},
						{
							search: true,
							label: "店铺状态",
							prop: "storeStatus",
							type: "select",
							dicData: Dict.STORE_STATUS_TYPE,
						},
						{
							label: "店铺平均分",
							prop: "storeAvgScore",
						},
						{
							label: '签约区域',
							prop: 'signingArea',
							value: 'signingArea',
							searchSpan:6,
							search: true,
							defaultExpandAll:false,
							hide: true,
							dicUrl:'/base/organization/listTreeByUserOrganization',
							type: 'tree',
							props: {
								label: 'name',
								value: 'id',
								children: 'childrenNodes'
							},
						},
						{
							label: "签约区域",
							prop: "organizationStr",
						},
						{
							label: "是否本人签约的店铺",
							prop: "isManageStore",
							type:'select',
							dicData:[{
								value:true,
								label:'是'
							},{
								value:false,
								label:'否'
							}]
						},
						{
							label: "是否本人签约的店铺",
							hide:true,
							search:true,
							searchLabelWidth:150,
							searchSpan:8,
							prop: "isCreateStoreAdmin",
							type:'select',
							dicData:[{
								value:true,
								label:'是'
							},{
								value:false,
								label:'否'
							}]
						},
					],
				},
				data: [],
			};
		},
		computed: {
			...mapGetters(["permission", 'userInfo', 'dictionariy']),
			permissionList() {
				return {

				};
			},
		},
		methods: {
			//编辑确认提交
			callback(data) {
				console.log(data)
				let form=this.getData(data,1);
				// if (data.validity == ''&&data.storeStatus!=-1) {
				// 	this.$message({type: "error", message: "请填写店铺有效期"});
				// 	return false;
				// }
				console.log(form);
				update(form).then(res => {
						if (res.data.code == 200) {
							this.$message({
								type: "success",
								message: "操作成功!"
							});
							this.onLoad(this.page);
							this.dialogFormVisible = false
						}else if (res.data.code == 500) {
							this.$message({
								type: "error",
								message: res.data.message
							});
						} else if (res.status == 500) {
							this.dialogFormVisible = false;
						}
					})
					.catch(err => {
						this.$message.error(err);
					})
			},
			//新增店铺
			addOption(data) {
				console.log(data);
				let form=this.getData(data,0);
				console.log(form)
				let datas={
					account:form.storeAccount || '',
					phone:form.dockingPeoplePhone || '',
					name:form.companyName || ''
				}
				//需要先请求注册用户接口，传入账号account，phone
				adminAddUser(datas).then(res => {
					console.log(res);
					if (res.status == 200) {
						if (res.data.code == 200) {
							//请求注册店铺接口
							setTimeout(item=>{
								this.adminRegisterStore(form);
							},2000)
						} else if (res.data.code == 500) {
							this.$message({
								type: "error",
								message: res.data.message
							});
						}else if (res.data.code == 401) {
							this.$confirm(res.data.message + "确定继续为此账号新增店铺?", {
								confirmButtonText: "确定",
								cancelButtonText: "取消",
								type: "warning"
							}).then(() => {
								//请求注册店铺接口
								this.adminRegisterStore(form);
							});
						}
					}else{
						this.$message({
							type: "error",
							message: res.data.message
						});
					}
				})
				.catch(err => {
					this.$message.error(err);
				});
			},
			handleRowClick (row) {
				this.currentGoodsName= "店铺名称："+ row.storeName
				getGoodsClassTreeNodesByIds(row.goodsClassIds).then(res=>{
					if(res.data.code==200){
						this.currentAreas =res.data.data
						this.currentGoodsVis=true

					}
				})
			},
			//注册店铺接口
			adminRegisterStore(data) {
				console.log(data)
				adminAddStore(data).then(res => {
					if (res.data.code == 200) {
						this.$message({
							type: "success",
							message: res.data.data
						});
						this.onLoad(this.page);
						this.dialogFormVisible = false;
					} else if (res.data.code == 500) {
						this.$message({
							type: "error",
							message: res.data.message
						});
					}
				})
				.catch(err => {
					this.$message.error(err);
				});
			},
			getData(data,type) {
				let obj={}
				if(type==0){//新增
					obj.storeAccount=data.storeAccount;
					obj.companyName=data.companyName;
					obj.storeName=data.storeName;
					obj.businessTerm=data.businessTerm;
					obj.commissionRate=data.commissionRate;
					obj.businessNo=data.businessNo;
					obj.storeType=data.storeType;
					obj.goodsClassIds=data.goodsClassIds;
					obj.taxNo=data.taxNo;
					obj.cycleType=data.cycleType;
					obj.monthsOrWeeks=data.monthsOrWeeks;
					obj.day=data.day;
					obj.signingArea=data.signingArea;
					obj.operatingArea=data.operatingArea;
					obj.tripartiteStoreId=data.tripartiteStoreId;
					obj.contractNo=data.contractNo || '';
					obj.bankId=data.bankId || '';
					obj.accountName=data.accountName || '';
					obj.accountNum=data.accountNum || '';
					obj.percentageCommission=data.percentageCommission || '';
					// obj.commissionRate=data.commissionRate;
					obj.storeLabel=data.storeLabel || '';
					obj.dockingPeoplePhone=data.dockingPeoplePhone || '';
					obj.payChannelId=data.payChannelId;
					obj.validity=data.validity;
				}else{//编辑
					delete data.$bankId;
					delete data.orthersImgs;
					delete data.$companyCity;
					delete data.$companyAreaId;
					delete data.$companyProvince;
					delete data.$storeType;
					delete data.$cycleType;
					delete data.$monthsOrWeeks;
					delete data.$storeLabel;
					delete data.$storeStatus;
					delete data.$goodsClassIds;
					delete data.noTime;
					obj=data
				}
				console.log(obj)
				return obj;
				//这个属性后台不需要，而且还会导致后台报错，所以移除了
				// delete data.$storeOwnerSex;
				// delete data.$getProvince;
				// delete data.$storeType;
				// delete data.$goodsClassId;
				// delete data.$companyProvince;
				// delete data.$postProvince;
				// delete data.$bankId;
				// delete data.$bankProvince;
				// delete data.$bankCity;
				// delete data.$gradeId;
				// delete data.$companyCity;
				// delete data.$companyAreaId;
				// delete data.$postCity;
				// delete data.$postArea;
				// delete data.$getCity;
				// delete data.$getArea;
				// delete data.$storeStatus;
				// delete data.$cycleType;
				// delete data.$goodsClassIds;
				// delete data.registerTime;
				// delete data.acTime;
			},
			//查看鼠标事件
			changeColor(val) {
				for (var item of this.paperWorkList) {
					if (item.id == val) {
						if (item.isOk) {
							item.isOk = false
						} else {
							item.isOk = true
						}
					}
				}
			},
			//查看证件图片
			viewMyPaper(imgUrl, name) {
				if (imgUrl == '') {
					this.$message.error('暂无相关证件')
				} else {
					this.innerVisible = true
					this.workImg.imgUrl = imgUrl
					this.workImg.name = name
				}
			},

			//查看证件弹框
			viewPaperWork(row) {
                this.checkList = [];
				this.dialogFormVisible2 = !this.dialogFormVisible2
				this.paperWorkList=[]
				getStoreDetail(row.id).then(res => {
					this.obj = res.data.data
					let businessLicense={
						id: 1,
						name: '营业执照',
						imgUrl:this.obj.businessLicense,
						isOk: false,
					}
					let operateLicenseImg={
						id: 2,
						name: '经营许可证',
						imgUrl: this.obj.operateLicenseImg,
						isOk: false,
					}
					let frontcardImg={
						id: 3,
						name: '身份证正面照',
						imgUrl: this.obj.frontcardImg,
						isOk: false,
					}
					let backcardImg={
						id: 4,
						name: '身份证反面照',
						imgUrl: this.obj.backcardImg,
						isOk: false,
					}
					let otherOne={
						id: 5,
						name: '其他证件1',
						imgUrl: this.obj.otherOne,
						isOk: false,
					}
					let otherTwo={
						id: 6,
						name: '其他证件2',
						imgUrl: this.obj.otherTwo,
						isOk: false,
					}
					let otherThree={
						id: 7,
						name: '其他证件3',
						imgUrl: this.obj.otherThree,
						isOk: false,
					}
					let otherFour={
						id: 8,
						name: '其他证件4',
						imgUrl: this.obj.otherFour,
						isOk: false,
					}
					let otherFive={
						id: 9,
						name: '其他证件5',
						imgUrl: this.obj.otherFive,
						isOk: false,
					}
					if(this.obj.businessLicense){
						this.checkList.push(1)
					}
					 if(this.obj.operateLicenseImg){
						this.checkList.push(2)
					}
					 if(this.obj.frontcardImg){
						this.checkList.push(3)
					}
					 if(this.obj.backcardImg){
						this.checkList.push(4)
					}
					 if(this.obj.otherOne){
						this.checkList.push(5)
					}
					 if(this.obj.otherTwo){
						this.checkList.push(6)
					}
					 if(this.obj.otherThree){
						this.checkList.push(7)
					}
					 if(this.obj.otherFour){
						this.checkList.push(8)
					}
					 if(this.obj.otherFive){
						this.checkList.push(9)
					}
					this.paperWorkList.push(businessLicense)
					this.paperWorkList.push(operateLicenseImg)
					this.paperWorkList.push(frontcardImg)
					this.paperWorkList.push(backcardImg)
					this.paperWorkList.push(otherOne)
					this.paperWorkList.push(otherTwo)
					this.paperWorkList.push(otherThree)
					this.paperWorkList.push(otherFour)
					this.paperWorkList.push(otherFive)
					console.log(this.checkList)
					console.log(this.paperWorkList)

				});
			},
			//关闭张证件弹框
			closeDialog2() {
				this.dialogFormVisible2 = false
			},
			//表格编辑
			edit(storeId) {
				console.log(storeId,'编辑时id-------')
				this.storeId = storeId
				this.title = "编辑店铺";
				this.isView = false
				this.dialogFormVisible = true
			},
			//查看店铺详情
			viewStore(storeId) {
				this.storeId = storeId
				this.title = "查看店铺";
				this.dialogFormVisible = true
				this.isView = true
			},
			//新增店铺
			addStore() {
				this.storeId = '';
				this.dialogFormVisible = true;
				this.title = "新增店铺";
				this.isView = false
			},
			//关闭店铺详情弹框
			closeDrawer() {
				this.dialogFormVisible = false
			},
			//相册弹框提交按钮
			submit1() {},
			//表格查看相册
			viewPic() {
				this.dialogFormVisible1 = !this.dialogFormVisible1
			},
			//关闭相册弹框
			closeDialog1() {
				this.dialogFormVisible1 = false

			},
			searchReset() {
				this.query = {};
				this.onLoad(this.page);
			},
			//搜索
			searchChange(params,done) {
				this.page.currentPage = 1
				this.query = params;
				this.onLoad(this.page, params,done);
			},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},
			refreshChange() {
				this.onLoad(this.page);
			},
			onLoad(page, params = {},done) {
				this.loading = true;
				getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
					if(done){
						done();
					}
					const data = res.data;
					this.page.total = data.count;
					for (let item of data.data) {
						if(item.areaId){
							getParentAndGrandInfoById(item.areaId).then(res => {
								item.allAreaName = res.data.data.allName
							}, (error) => {
								this.$message({
									type: 'error',
									message: error
								})
							});
						}
					}
					this.data = data.data;
					this.loading = false;
				});
			}
		}
	};
</script>

<style scoped>
	.activeBut {
		background-color: #333333;
		color: #FFFFFF;
	}

	.formTitle {
		font-size: 0.7rem;
		color: #000000;
	}

	.input {
		width: 200px;
	}

	.paperWork {
		height: 40px;
		line-height: 40px;
	}

	.el-checkbox {
		width: 50%;
		margin-left: 150px;
	}

	.checkPaper {
		color: #000000;
	}

	.checkPaper1 {
		color: red;
	}

	.img {
		width: 300px;
		height: auto;
	}
</style>
